/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlImagen;
import Controlador.ControlProdServ;
import Controlador.ControlProveedor;
import Modelo.Imagen;
import Modelo.Producto;
import Modelo.Proveedor;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.jdesktop.swingx.JXSearchField;

/**
 *
 * @author Damian
 */
public class PnlProd extends javax.swing.JPanel {

    /**
     * Creates new form PnlProd
     */
    TableRowSorter<TableModel> rs;
    ControlProveedor controlp = new ControlProveedor();
    ArrayList<Proveedor> l;

    public PnlProd() {
        initComponents();
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
        }
        tablaProd.setModel(modeloProductos());

        rs = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rs);

        txtBuscar.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        filtrar();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        filtrar();
                    }
                });
    }

    public TableRowSorter<TableModel> getRs() {
        return rs;
    }

    public void setRs(TableRowSorter<TableModel> rs) {
        this.rs = rs;
    }

    public ControlProveedor getControlp() {
        return controlp;
    }

    public void setControlp(ControlProveedor controlp) {
        this.controlp = controlp;
    }

    public ArrayList<Proveedor> getL() {
        return l;
    }

    public void setL(ArrayList<Proveedor> l) {
        this.l = l;
    }

    public JLabel getjLabel1() {
        return jLabel1;
    }

    public void setjLabel1(JLabel jLabel1) {
        this.jLabel1 = jLabel1;
    }

    public JScrollPane getjScrollPane1() {
        return jScrollPane1;
    }

    public void setjScrollPane1(JScrollPane jScrollPane1) {
        this.jScrollPane1 = jScrollPane1;
    }

    public JTable getTablaProd() {
        return tablaProd;
    }

    public void setTablaProd(JTable tablaProd) {
        this.tablaProd = tablaProd;
    }

    public JXSearchField getTxtBuscar() {
        return txtBuscar;
    }

    public void setTxtBuscar(JXSearchField txtBuscar) {
        this.txtBuscar = txtBuscar;
    }

    

    private void filtrar() {
        RowFilter<TableModel, Object> rf = null;
        try {
            rf = RowFilter.regexFilter(("(?i)") + txtBuscar.getText(), 1, 2, 5);
        } catch (java.util.regex.PatternSyntaxException e) {
        }
        rs.setRowFilter(rf);
    }

    public int prodSeleccionado() throws ArrayIndexOutOfBoundsException{

        int i = tablaProd.getSelectedRow();
        i = rs.convertRowIndexToModel(i);
        String cod = ((DefaultTableModel) tablaProd.getModel()).getValueAt(i, 0).toString();
        i = Integer.parseInt(cod);
        return i;
    }

    public DefaultTableModel modeloProductos() {
        try {
            l = controlp.listar();
        } catch (SQLException ex) {
        }
        String[] columnas = {"Código", "Nombre", "Descripción", "Precio", "Promoción", "Proveedor"};
        DefaultTableModel tabla = new DefaultTableModel(columnas, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false; //To change body of generated methods, choose Tools | Templates.
            }

        };
        ArrayList<Producto> lista = new ControlProdServ().listarProductos();

        for (int i = 0; i < lista.size(); i++) {
            Producto prod = lista.get(i);

            tabla.addRow(new Object[]{prod.getCodigo(), prod.getNombre(),
                prod.getDescripcion(), prod.getPrecioUnitario(),
                prod.getCodPromocion()==-1?"":prod.getCodPromocion(),
                proveedorMostrar(prod.getCodProveedor())});
        }
        return tabla;
    }

    public String proveedorMostrar(String cod) {
        String r = "";

        for (int i = 0; i < l.size(); i++) {
            Proveedor proveedor = l.get(i);
            if (proveedor.getCodigo().equals(cod)) {
                r = cod + "-" + proveedor.getEmpresa();
                break;
            }
        }

        return r;
    }

    public void actualizar() {
        tablaProd.setRowSorter(null);
        rs = null;
        tablaProd.setModel(modeloProductos());
        rs = new TableRowSorter<>(tablaProd.getModel());
        tablaProd.setRowSorter(rs);
        filtrar();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaProd = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtBuscar = new org.jdesktop.swingx.JXSearchField();

        setLayout(new java.awt.BorderLayout());

        tablaProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tablaProd);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jLabel1.setText("Buscar:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(78, 78, 78)
                .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        add(jPanel1, java.awt.BorderLayout.PAGE_START);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaProd;
    private org.jdesktop.swingx.JXSearchField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
